//
//  ChatTabBarView.m
//  EaseMob
//
//  Created by 王方伟 on 16/7/26.
//  Copyright © 2016年 wfw. All rights reserved.
//

#import "ChatTabBarView.h"
#import "FWCustomTextView.h"

@interface ChatTabBarView ()<UITextViewDelegate>
@property (weak, nonatomic) IBOutlet FWCustomTextView *textView;
@property (weak, nonatomic) IBOutlet UIButton *leftBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tabBarViewH;

@property (weak, nonatomic) IBOutlet UIButton *voiceBtn;
@end

@implementation ChatTabBarView

+ (instancetype)chatTabBarView{
    return [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil].lastObject;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    _textView.delegate = self;
    _textView.placeholder = @"输入新消息";
}

- (IBAction)onClicVoice:(id)sender {
    _voiceBtn.hidden = !_voiceBtn.isHidden;
    if (_voiceBtn.isHidden == NO) {
        self.tabBarViewH.constant = 44;
        [self.textView endEditing:YES];
        [_leftBtn setImage:[UIImage imageNamed:@"chatBar_keyboard"] forState:UIControlStateNormal];
    }else{
        [_leftBtn setImage:[UIImage imageNamed:@"chatBar_record"] forState:UIControlStateNormal];
        [_textView becomeFirstResponder];
        [self textViewDidChange:_textView];
    }
}

#pragma 开始录音
- (IBAction)beginRecord:(id)sender {
    if ([_delegate respondsToSelector:@selector(onCllickBeginVoiceBtn)]) {
        [_delegate onCllickBeginVoiceBtn];
    }
   
}

#pragma 结束录音
- (IBAction)endRecord:(id)sender {
    if ([_delegate respondsToSelector:@selector(onClickendVoiceBtn)]) {
        [_delegate onClickendVoiceBtn];
    }
    
}

- (IBAction)cancelRecord:(id)sender {
    if ([_delegate respondsToSelector:@selector(onClickCancelVoiceBtn)]) {
        [_delegate onClickCancelVoiceBtn];
    }
}

- (void)textViewDidChange:(UITextView *)textView{
    CGFloat height = 0.0;
    CGFloat minHeight = 44;
    CGFloat maxHeight = 88;
    CGFloat contentHeight = textView.contentSize.height;
    if (contentHeight > maxHeight) {
        height = maxHeight;
    }else if (contentHeight < minHeight){
        height = minHeight;
    }else{
        height = contentHeight;
    }
    
    if ([textView.text hasSuffix:@"\n"]) {
        textView.text = [textView.text substringToIndex:textView.text.length - 1];
        if ([_delegate respondsToSelector:@selector(onClickSendMessage:)]) {
            [_delegate onClickSendMessage:textView.text];
        }
        textView.text = nil;
        height = minHeight;
        [textView setContentOffset:CGPointZero animated:YES];
    }
    MyLog(@"%f", height);
    [UIView animateWithDuration:0.2 animations:^{
        self.tabBarViewH.constant = height;
    }];
}

@end
